import React, { PureComponent, ReactNode } from 'react';
import { connect, SubscriptionAPI } from 'dva';
import { Row, Col, Popconfirm, Form, Input, message } from 'antd';
import { Badge, Icon, PopupDialog, Button } from 'components';
import centos from 'assets/centos.png';
import debian from 'assets/debian.png';
import suse from 'assets/suse.png';
import ubuntu from 'assets/ubuntu.png';
import windows from 'assets/windows.png';
import { ListType, ListItem } from '../../models/agent';
import styles from './index.less';

interface Props extends SubscriptionAPI{
  data: ListType;
}

const formValues: ListItem = {
  status: '',
  type: '',
  resources: [],
  ip: '',
  os: '',
  name: '',
  id: 0,
  location: '',
};
const ImageCompoent = (str: string): ReactNode => {
  const src = {
    centos,
    debian,
    suse,
    ubuntu,
    windows,
  }[str];

  return src ? <img src={src} alt={str}/> : '';
};

const CreateTagForm = connect()(
  Form.create()((props: any) => {
    const {
      form: { getFieldDecorator, validateFields, resetFields } ,
      visible,
      onModalVisible,
      dispatch,
      initValues,
      top,
      left,
    } = props;

    const handleOk = () => {
      validateFields((err: any, fields: { tag: string }) => {
        if (!err) {
          dispatch({
            type: `agent/changeTag`,
            payload: {
              instance: initValues,
              ...fields,
            },
            callback: () => {
              message.success('创建成功');
              onModalVisible(false);
              resetFields();
            },
            mark: 'create',
          });
        }
      });
    };

    const handleCancel = () => {
      onModalVisible(false);
      resetFields();
    };

    return (
      <PopupDialog
        visible={visible}
        title="Separate multiple resource name with commas"
        onOk={handleOk}
        onCancel={handleCancel}
        top={top}
        left={left}
      >
        <Form.Item>
          {getFieldDecorator('tag', {
            rules: [{ required: true, message: 'Separate multiple resource name with commas' }],
          })(<Input placeholder="Input value" />)}
        </Form.Item>
      </PopupDialog>
    )
  })
);

@connect(({ agent }: any) => agent)
class InstanceCard extends PureComponent<Props> {
  state = {
    visible: false,
    initValues: formValues,
    left: 0,
    top: 0
  };

  onDelete = (instance: ListItem, tag: string) => {
    this.props.dispatch({
      type: 'agent/changeTag',
      payload: {
        instance,
        tag,
      },
      callback: () => {
        message.success('删除成功');
      },
      mark: 'delete',
    })
  };

  onModalVisible = (visible: boolean, instance?: ListItem, e?: any) => {
    // e.preventDefault();
    if (e) {
      const { clientX, clientY } = e;
      console.log(clientX, clientY);
      this.setState({
        left: clientX - 55,
        top: clientY + 30,
      })
    }
    this.setState({
      visible,
      initValues: instance,
    })
  };

  render () {
    const { visible, initValues, left, top } = this.state;
    const { data } = this.props;

    return (
      <>
        <div style={{ marginTop: '18px' }}>
          {
            data.map((item: ListItem) =>(
              <Row key={item.id} className={styles.wrapper}>
                <Col span={3}>
                  {
                    ImageCompoent(item.os)
                  }
                </Col>
                <Col span={21}>
                  <Row className={styles['wrapper-top']} type="flex" align="middle">
                    <Icon type="desktop" size="large" />
                    <span className={styles.name}>{item.name}</span>
                    <Badge style={{ marginLeft: '30px', marginRight: '20px' }} color={item.status === 'building' ? '#FF9A2A': '#7FBC39'} size="small">{item.status}</Badge>
                    <Icon type="info" size="large" />
                    <span className={styles.ip}>{item.ip}</span>
                    <Icon type="folder" size="large" />
                    <span className={styles.location}>{item.location}</span>
                  </Row>
                  <Row className={styles['wrapper-bottom']} type="flex" justify="space-between" align="middle">
                    <Col>
                      <Button icon="plus" type="primary" onClick={(e: any) => this.onModalVisible(true, item, e)} />
                      {
                        item.resources.length && (
                          item.resources.map(val => (
                            <span className={styles.tag} key={val}>
                            {val}
                              <Popconfirm title="是否要删除此行？" onConfirm={() => this.onDelete(item, val)}>
                              <Icon type="trash" size="small" />
                            </Popconfirm>
                          </span>
                          ))
                        )
                      }
                    </Col>
                    <Col>
                      <Button icon="deny" type="primary">
                        <span style={{ marginLeft: '8px' }}>Deny</span>
                      </Button>
                    </Col>
                  </Row>
                </Col>
              </Row>
            ))
          }
        </div>
        <CreateTagForm
          visible={visible}
          onModalVisible={this.onModalVisible}
          initValues={initValues}
          left={left}
          top={top}
        />
      </>
    )
  }
}

export default InstanceCard;
